package com.sumer.queue;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.TimeUnit;

/**
 * 队列测试
 */
public class QueueTest {

    public static void main(String[] args) throws InterruptedException {
//        test1();
//        test2();
//        test3();
        test4();
    }

    public static void test1(){
        ArrayBlockingQueue<String> queue = new ArrayBlockingQueue<>(3);
        System.out.println(queue.add("a"));
        System.out.println(queue.add("b"));
        System.out.println(queue.add("c"));
        // Exception in thread "main" java.lang.IllegalStateException: Queue full
        // 抛出异常  队列已满
//        System.out.println(queue.add("d"));
        System.out.println(queue.element());
        System.out.println(queue.remove());
        System.out.println(queue.remove());
        System.out.println(queue.remove());
        // 抛出异常  队列为null
//        System.out.println(queue.remove());
    }

    public static void test2(){
        ArrayBlockingQueue<String> queue = new ArrayBlockingQueue<>(3);
        System.out.println(queue.offer("a"));
        System.out.println(queue.offer("b"));
        System.out.println(queue.offer("c"));
        // 队列已满  不抛出异常 返回false
//        System.out.println(queue.offer("d"));
        System.out.println(queue.element());

        System.out.println(queue.poll());
        System.out.println(queue.poll());
        System.out.println(queue.poll());
        // 队列为null 不抛出异常  返回null
        System.out.println(queue.poll());
        // 队列为null 不抛出异常 返回null
        System.out.println(queue.peek());
    }


    public static void test3() throws InterruptedException {
        ArrayBlockingQueue<String> queue = new ArrayBlockingQueue<>(3);
        queue.put("a");
        queue.put("b");
        queue.put("c");
        // 队列已满  一直等待
        //queue.put("d");
        System.out.println(queue.take());
        System.out.println(queue.take());
        System.out.println(queue.take());
        // 队列为null 一直等待
        System.out.println(queue.take());
    }

    public static void test4() throws InterruptedException {
        ArrayBlockingQueue<String> queue = new ArrayBlockingQueue<>(3);
        // 超时阻塞
        System.out.println(queue.offer("a",2, TimeUnit.SECONDS));
        System.out.println(queue.offer("b",2, TimeUnit.SECONDS));
        System.out.println(queue.offer("c",2, TimeUnit.SECONDS));
        // 队列已满  超时返回false
        System.out.println(queue.offer("d",2, TimeUnit.SECONDS));

        System.out.println(queue.poll(2,TimeUnit.SECONDS));
        System.out.println(queue.poll(2,TimeUnit.SECONDS));
        System.out.println(queue.poll(2,TimeUnit.SECONDS));
        // 队列为null  超时返回null
        System.out.println(queue.poll(2,TimeUnit.SECONDS));
    }
}
